<template>
  <div class="new-page">
    <div class="toolbar">
      <div class="toolbar-group">
        <select ref="fontSize" @change="changeFontSize" class="tool-item">
          <option value="14px">14px</option>
          <option value="16px" selected>16px</option>
          <option value="18px">18px</option>
          <option value="20px">20px</option>
          <option value="24px">24px</option>
        </select>
        <select ref="headingLevel" @change="setHeading" class="tool-item">
          <option value="P">普通文本</option>
          <option value="H1">标题 1</option>
          <option value="H2">标题 2</option>
          <option value="H3">标题 3</option>
          <option value="H4">标题 4</option>
          <option value="H5">标题 5</option>
          <option value="H6">标题 6</option>
        </select>
      </div>

      <div class="toolbar-group">
        <button @click="toggleBold" class="tool-btn" title="加粗">加粗</button>
        <button @click="toggleItalic" class="tool-btn" title="倾斜">倾斜</button>
        <button @click="toggleUnderline" class="tool-btn" title="下划线">下划线</button>
        <button @click="toggleStrikethrough" class="tool-btn" title="删除线">删除线</button>
        <button @click="insertLink" class="tool-btn" title="插入链接">链接</button>
      </div>

      <div class="toolbar-group">
        <button @click="insertUnorderedList" class="tool-btn" title="无序列表">无序列表</button>
        <button @click="insertOrderedList" class="tool-btn" title="有序列表">有序列表</button>
        <button @click="indent" class="tool-btn" title="增加缩进">增加缩进</button>
        <button @click="outdent" class="tool-btn" title="减少缩进">减少缩进</button>
      </div>

      <div class="toolbar-group">
        <input type="color" ref="textColor" @change="changeTextColor" title="选择文字颜色" class="color-picker">
      </div>
      <div class="toolbar-group">
        <button @click="undo" class="tool-btn" title="撤销">撤销</button>
        <button @click="redo" class="tool-btn" title="重做">重做</button>
      </div>
    </div>

    <div class="cover-image-section">
      <div class="cover-image" :style="coverImageStyle">
        <img :src="filePath" width="50" height="50" style="border-radius: 100px">
        <Upload :before-upload="upload">
          <Button icon="ios-cloud-upload-outline">点击上传封面图片</Button>
        </Upload>
      </div>
    </div>

    <div ref="title" id="title" contenteditable="true" @input="onTitleInput" :class="{'error': titleError}">
      <h1 style="text-align: center">自定义标题</h1>
    </div>
    <div v-if="titleError" class="error-message">标题不能为空</div>

    <div ref="editor" class="editor" contenteditable="true" @input="onEditorInput" :class="{'error': contentError}"></div>
    <div v-if="contentError" class="error-message">内容不能为空</div>

    <div class="word-count">
      字数：{{ wordCount }}
    </div>

    <div class="button-container">
      <button @click="publish" class="publish-btn" :disabled="publishing">
        {{ publishing ? '发布中...' : '发布' }}
      </button>
    </div>

    <div v-if="showPreview" class="preview-modal">
      <div class="preview-content">
        <div class="preview-header">
          <h2>预览</h2>
          <button @click="closePreview" class="close-btn">×</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import {fileUpload, friendUpdatesSave} from "@/api/api";
import debounce from 'lodash/debounce';

export default {
  name: "NewPage",
  data() {
    return {
      filePath: "",
      titleError: false,
      contentError: false,
      publishing: false,
      showPreview: false,
      showSaveHint: false,
      wordCount: 0,
      coverImage: null,
      lastSavedContent: '',
      lastSavedTitle: ''
    }
  },
  computed: {
    coverImageStyle() {
      return this.coverImage ? {
        backgroundImage: `url(${this.coverImage})`,
        backgroundSize: 'cover',
        backgroundPosition: 'center'
      } : {}
    }
  },

  methods: {
    publish() {
      const title = this.$refs.title.textContent
      const styleTitle = this.$refs.title.innerHTML
      const content = this.$refs.editor.textContent
      const styleContent = this.$refs.editor.innerHTML
      const img = this.filePath

      friendUpdatesSave({title, styleTitle, content, styleContent, img}).then(res => {
        if (res.data.code == 1) {
          this.$Message.success("发布成功")
        } else {
          this.$Message.success("服务器崩溃")
        }
      })
    },

    changeFontSize() {
      const size = this.$refs.fontSize.value;
      document.execCommand("fontSize", false, "7");
      let fontElements = document.querySelectorAll("font[size='7']")
      fontElements.forEach(el => {
        el.removeAttribute("size")
        el.style.fontSize = size
      })
    },

    setHeading() {
      const level = this.$refs.headingLevel.value;
      document.execCommand("formatBlock", false, level);
    },

    toggleBold() {
      document.execCommand("bold")
    },
    toggleStrikethrough() {
      document.execCommand("strikethrough")
    },
    toggleItalic() {
      document.execCommand("italic")
    },

    toggleUnderline() {
      document.execCommand("underline")
    },

    insertLink() {
      const url = prompt('请输入链接地址：', 'https://');
      if (url) {
        document.execCommand('createLink', false, url);
      }
    },

    insertUnorderedList() {
      document.execCommand('insertUnorderedList');
    },

    insertOrderedList() {
      document.execCommand('insertOrderedList');
    },

    indent() {
      document.execCommand('indent');
    },

    outdent() {
      document.execCommand('outdent');
    },

    undo() {
      document.execCommand('undo');
    },

    redo() {
      document.execCommand('redo');
    },

    upload(file) {
      this.file = file
      let formData = new FormData();
      formData.append('file', this.file);

      fileUpload(formData).then(res => {
        if (res.body.code != 1) {
          this.$Message.error(res.body.msg)
          return
        }
        this.filePath = res.body.data
      })
    },

    onEditorInput() {
      this.validateContent();
      this.updateWordCount();
      this.showSaveHint = true;
      this.autoSave();
    },

    onTitleInput() {
      this.validateTitle();
      this.showSaveHint = true;
      this.autoSave();
    },

    updateWordCount() {
      const text = this.$refs.editor.textContent;
      this.wordCount = text.trim().replace(/\s+/g, ' ').length;
    },

    preview() {
      this.showPreview = true;
    },

    closePreview() {
      this.showPreview = false;
    },

    changeTextColor() {
      document.execCommand("foreColor", false, this.$refs.textColor.value)
    },

    validateTitle() {
      this.titleError = !this.$refs.title.textContent.trim();
    },

    validateContent() {
      this.contentError = !this.$refs.editor.textContent.trim();
    }
  }
}
</script>

<style scoped>
.new-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.toolbar {
  background: #f5f5f5;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 10px;
  margin-bottom: 20px;
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.toolbar-group {
  display: flex;
  gap: 5px;
  align-items: center;
  padding: 0 10px;
  border-right: 1px solid #ddd;
}

.toolbar-group:last-child {
  border-right: none;
}

.tool-btn {
  padding: 6px 12px;
  background: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.tool-btn:hover {
  background: #e9ecef;
}

.tool-item {
  padding: 6px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: white;
}

.color-picker {
  width: 40px;
  height: 30px;
  padding: 0;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

#title {
  width: 100%;
  min-height: 60px;
  margin: 20px 0;
  padding: 15px;
  font-size: 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  transition: all 0.3s;
}

.editor {
  width: 100%;
  min-height: 300px;
  margin: 20px 0;
  padding: 15px;
  font-size: 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  transition: all 0.3s;
}

.error {
  border-color: #ff4d4f;
}

.error-message {
  color: #ff4d4f;
  font-size: 14px;
  margin-top: -15px;
  margin-bottom: 15px;
}

.button-container {
  text-align: center;
  margin-top: 20px;
}

.publish-btn {
  padding: 10px 30px;
  font-size: 16px;
  color: white;
  background-color: #1890ff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.publish-btn:hover {
  background-color: #40a9ff;
}

.publish-btn:disabled {
  background-color: #d9d9d9;
  cursor: not-allowed;
}

.save-hint {
  position: fixed;
  top: 20px;
  right: 20px;
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 10px 20px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
  z-index: 1000;
}

.hint-btn {
  background: #1890ff;
  color: white;
  border: none;
  padding: 4px 8px;
  border-radius: 4px;
  cursor: pointer;
}

.cover-image-section {
  margin: 20px 0;
}

.cover-image {
  width: 100%;
  height: 300px;
  border: 2px dashed #ddd;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background-color: #f8f8f8;
  transition: all 0.3s;
}

.cover-image:hover {
  border-color: #1890ff;
}

.upload-hint {
  color: #666;
  font-size: 16px;
}

.word-count {
  text-align: right;
  color: #666;
  margin-top: 10px;
}

.secondary-btn {
  padding: 10px 20px;
  font-size: 16px;
  color: #666;
  background-color: white;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  margin-right: 10px;
}

.secondary-btn:hover {
  border-color: #1890ff;
  color: #1890ff;
}

.preview-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.preview-content {
  background: white;
  width: 80%;
  max-width: 1000px;
  height: 80vh;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.preview-header {
  padding: 20px;
  border-bottom: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.preview-body {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.preview-title {
  margin-bottom: 20px;
}

.preview-content-body {
  line-height: 1.6;
}
</style>